package com.forte.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.forte.model.ShoppingCustomerModel;
import com.forte.shoppingcustomer.ShoppingCustomerService;
import com.forte.shoppingcustomerdao.ShoppingCustomer;
import com.forte.util.Pages;
import com.forte.util.Utility;

@Controller
public class RegisterController {
	
	public static final String REGISTER_VIEW_MODEL = "customer";
	
	@Autowired
	@Qualifier("shoppingCustomerService")
	private ShoppingCustomerService shoppingCustomerService;
	
		
	@RequestMapping(value="/signup.do")
	public String callSignUp(Model model){
		model.addAttribute("customer", new ShoppingCustomerModel());
		return "cartreg";
	}
	
	@RequestMapping(value="/signup.do", method= RequestMethod.POST)
	public String signUp(@Valid  @ModelAttribute("customer") ShoppingCustomerModel customer, BindingResult result, Model model)
	{
		String returnPage = Pages.CARTREG.getValue();
		if(!result.hasErrors())
			{
				ShoppingCustomer findCustomer = shoppingCustomerService.findCustomerByEmail(customer.getemail());
				if(findCustomer == null)
				{
					ShoppingCustomer newCustomer = save(customer);
					shoppingCustomerService.saveOrUpdate(newCustomer);
					model.addAttribute("success", "Your registration was successful. Start shopping! ");
				    returnPage = Pages.REGISTERSUCCESS.getValue();
				}
				result.addError(new FieldError(REGISTER_VIEW_MODEL, "email", "This email has been taken. Please try another email."));
			}
			//Redisplay the registration for if there is error.
			return returnPage;
	}
	
	 private ShoppingCustomer save(ShoppingCustomerModel model)
		{			
			ShoppingCustomer newCustomer = new ShoppingCustomer();		
			newCustomer.setPassword(model.getpassword());
			newCustomer.setEmail(model.getemail());
			newCustomer.setCreatedDate(Utility.currentDate);
			return newCustomer;
		}

}
